package com.wrox;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;

import com.wrox.locator.DataSourceLocator;
import com.wrox.locator.ServiceConstant;


public class EditEmployeeAction extends Action {

  protected void editEmployee(EmployeeForm form, HttpServletRequest request)
    throws Exception {

    Employee employee = new Employee();

    employee.setPassword(form.getPassword());
    Department department = new Department();
	department.setDepID(new Integer(form.getDepid()));
	employee.setDepartment(department);
	Role role = new Role();
	role.setRoleID(new Integer(form.getRoleid()));
	employee.setRole(role);
   // employee.setRoleid(new Integer(form.getRoleid()));
    employee.setName(form.getName());
    employee.setPhone(form.getPhone());
    employee.setEmail(form.getEmail());
    //employee.setDepid(new Integer(form.getDepid()));
    employee.setUsername(form.getUsername());

    EmployeeData.updateEmployee(employee, DataSourceLocator.getInstance().getDataSources(ServiceConstant.SERVICE_CONSTANT));
  }

  public ActionForward execute(ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException {

    // Default target to success
    String target = new String("success");

    if ( isCancelled(request) ) {

      // Cancel pressed back to employee list
      return (mapping.findForward("success"));
    }

    try {

      editEmployee((EmployeeForm) form, request);
    }
    catch ( Exception e ) {

      System.err.println("Setting target to error");
      target = new String("error");
      ActionErrors errors = new ActionErrors();

      errors.add(ActionErrors.GLOBAL_MESSAGE,
        new ActionMessage("errors.database.error",
          e.getMessage()));

      // Report any errors
      if ( !errors.isEmpty() ) {

        saveErrors(request, errors);
      }
    }
    // Forward to the appropriate View
    return (mapping.findForward(target));
  }
}